/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ecom.tags;

import ecom.entity.Customer;
import ecom.session.EcomEuroConverterLocal;
import java.io.IOException;
import javax.ejb.EJB;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;
import javax.servlet.jsp.tagext.SimpleTagSupport;

/**
 * Tag qui permet de gerer le prix en fonction de l'internationnalisation
 * @author simon
 */
public class PriceTag extends SimpleTagSupport {

    @EJB
    private EcomEuroConverterLocal euroConverter;
    private String localString;
    private double price;

    @Override
    public void doTag() throws JspException, IOException {
        JspWriter out = getJspContext().getOut();
        Customer customer = (Customer) getJspContext().getAttribute("customer", PageContext.SESSION_SCOPE);
        
        double priceRounded = floor(euroConverter.getPriceByCurrency(this.price, customer, localString), 2);

        out.print(priceRounded + " " + euroConverter.getSymbol());
    }

    public void setLocalString(String localString) {
        this.localString = localString;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    /**
     * Arrondi d'un double avec n éléments après la virgule.
     * @param a La valeur à convertir.
     * @param n Le nombre de décimales à conserver.
     * @return La valeur arrondi à n décimales.
     */
    public static double floor(double a, int n) {
        double p = Math.pow(10.0, n);
        return Math.floor((a * p) + 0.5) / p;
    }
}
